﻿using System;
using System.Collections;
using System.Web;
using System.Web.Caching;

namespace Common
{
    public class WebCacheHelper
    {
        private static Cache webCache = HttpRuntime.Cache;

        #region 更新缓存

        /// <summary>
        /// 更新缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expireTime"></param>
        /// <returns></returns>
        public static bool UpdateCache(string key, object value, DateTime? expireTime = null)
        {
            bool result = true;

            try
            {
                webCache.Insert(key, value, null, expireTime ?? DateTime.MaxValue, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
            }
            catch (Exception ex)
            {
                LogHelper.Error($"报错：{ex}");
                result = false;
            }

            return result;
        }

        #endregion

        #region 删除缓存

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool RemoveCache(string key)
        {
            bool result = true;

            if (IsExistCache(key))
            {
                result = webCache.Remove(key) != null;
            }

            return result;
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <returns></returns>
        public static bool RemoveCache()
        {
            IDictionaryEnumerator cacheEnum = webCache.GetEnumerator();
            while (cacheEnum.MoveNext())
            {
                webCache.Remove(cacheEnum.Key.ToString());
            }

            return true;
        }

        #endregion

        #region 查询缓存

        /// <summary>
        /// 缓存个数
        /// </summary>
        /// <returns></returns>
        public static int GetCacheCount()
        {
            return webCache.Count;
        }

        /// <summary>
        /// 是否存在对应key值的缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool IsExistCache(string key)
        {
            return webCache.Get(key) != null;
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetCache<T>(string key) where T : class
        {
            return webCache.Get(key) as T;
        }

        #endregion

    }
}
